﻿using AuthCenter.Domain;
using AuthCenter.ErorCode;
using AuthCenter.Infrastructure;
using AuthCenter_API.Read.Applications.Commands.RBAC;
using AuthCenter_API.Read.Dtos;
using MediatR;

namespace AuthCenter_API.Read.Applications.CommandHandlers.RBAC
{
    public class MenuQueryCommandHandler : IRequestHandler<MenuQueryCommand, APIResult<APIPaging<MenuDto>>>
    {
        private readonly IBaseRepository<MenuModel> _menuRepository;

        public MenuQueryCommandHandler(IBaseRepository<MenuModel> menuRepository)
        {
            _menuRepository = menuRepository;
        }

        public Task<APIResult<APIPaging<MenuDto>>> Handle(MenuQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPaging<MenuDto>> result = new APIResult<APIPaging<MenuDto>>();
            result.Code = APIEnum.QuerySuccess;
            result.Message = APIEnum.QuerySuccess.Desc();
            var m = from a in _menuRepository.GetAll()
                    join b in _menuRepository.GetAll()
                    .DefaultIfEmpty() on a.PID equals b.MenuId into ab
                    from b in ab.DefaultIfEmpty()
                    where a.IsDel==0
                    select new MenuDto
                    {
                        MenuId = a.MenuId,
                        MenuName = a.MenuName,
                        Url = a.Url,
                        PID = a.PID,
                        CreateName = a.CreateName,
                        CreateTime = a.CreateTime,
                        UpdateName = a.UpdateName,
                        UpdateTime = a.UpdateTime,
                        OrderId = a.OrderId,
                        PName = b.MenuName
                    };
            var count = m.Count();
            var page = (int)Math.Ceiling(1.0 * count / request.Size);
            m = m.OrderByDescending(x => x.MenuId).Skip((request.Index - 1) * request.Size).Take(request.Size);
            APIPaging<MenuDto> p = new APIPaging<MenuDto>();
            p.TotalPage = page;
            p.TotalCount = count;
            p.List = m.ToList();
            result.Data = p;
            return Task.FromResult(result);
        }
    }
}
